<?php

namespace SinoPHP\BbdBoss\Library;

use ErrorException;
use SinoPHP\BbdBoss\Model\AppAccount;

/**
 * APP应用管理
 */
class AppAuth {

    /**
     * @var AppAccount
     */
    protected $appAccount;

    public function __construct() {
        $this->appAccount = model('AppAccount');
    }

    /**
     * Create a App account by random
     *
     * @param  string $appName
     * @return array
     * @throws ErrorException
     */
    public function createAppByRandom($appName) {
        return $this->createApp($appName, $this->randomPassword(32), $this->randomPassword(16));
    }

    /**
     * Create a App account
     *
     * @param  string $appName
     * @param  string $secret
     * @param  string $encodingKey
     * @return array
     * @throws ErrorException
     */
    public function createApp($appName, $secret, $encodingKey) {
        if (strlen($encodingKey) > 32) {
            throw new ErrorException('encodingKey长度不可超过32位', 101004);
        }

        if (strlen($secret) != 32) {
            throw new ErrorException('secret长度必须为32位', 101005);
        }

        if ($this->appAccount->has(['app_name' => $appName])) {
            throw new ErrorException('应用名称已存在: ' . $appName, 101002);
        }

        $data = array(
            'app_id' => substr(sha1($appName . time()), 0, 16),
            'app_name' => $appName,
            'secret' => $secret,
            'encoding_key' => $encodingKey,
            'create_time' => time(),
            'update_time' => time(),
        );

        if ($this->appAccount->insert($data) === false) {
            throw new ErrorException('应用创建失败, 请重试', 101003);
        }

        return $data;
    }

    /**
     * 签名算法
     *
     * @param  string $appId
     * @param  string $secret
     * @param  string $encodingKey
     * @return string
     */
    public function signature($appId, $secret, $encodingKey) {
        return sha1($appId . $secret . $encodingKey);
    }

    /**
     * Generate a random password
     *
     * @param  integer $length
     * @return string
     */
    protected function randomPassword($length = 8) {
        // Password chars
        $chars = array(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
            'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9',
        );

        shuffle($chars);
        $keys = array_rand($chars, $length);

        $password = '';
        foreach ($keys as $key) {
            $password .= $chars[$key];
        }

        return $password;
    }

}